package com.hifar.demo2;

import org.apache.poi.xwpf.usermodel.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.regex.*;

public class TemplateProcessor {

    public static void processTemplate(String templatePath,
            String xmlPath,
            String outputPath) {
        try {
            // 1. 加载模板文件
            XWPFDocument doc = new XWPFDocument(new FileInputStream(templatePath));

            // 2. 解析XML文件获取表格数据
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 明确指定使用 org.w3c.dom.Document 以解决类型模糊问题
            DocumentBuilder builder = null;

            try {
                builder = factory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            }
            org.w3c.dom.Document xmlDoc = null;
            try {
                xmlDoc = builder.parse(new File(xmlPath));
            } catch (Exception e) {
                e.printStackTrace();
            }
            xmlDoc = factory.newDocumentBuilder().parse(new File(xmlPath));

            // 3. 处理段落中的标签
            for (XWPFParagraph p : doc.getParagraphs()) {
                String text = p.getText();
                if (text != null) {
                    // 处理{{tableTitle}}标签
                    if (text.contains("{{tableTitle}}")) {
                        NodeList titles = xmlDoc.getElementsByTagName("title");
                        if (titles.getLength() > 0) {
                            String title = titles.item(0).getTextContent();
                            replaceTag(p, "{{tableTitle}}", title);
                        }
                    }

                    // 处理{{tableTitleN}}标签
                    Matcher m = Pattern.compile("\\{\\{tableTitle(\\d+)\\}\\}").matcher(text);
                    while (m.find()) {
                        int index = Integer.parseInt(m.group(1)) - 1;
                        NodeList titles = xmlDoc.getElementsByTagName("title");
                        if (index < titles.getLength()) {
                            String title = titles.item(index).getTextContent();
                            replaceTag(p, m.group(0), title);
                        }
                    }
                }
            }

            // 4. 处理表格中的标签
            for (XWPFTable tbl : doc.getTables()) {
                for (XWPFTableRow row : tbl.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph p : cell.getParagraphs()) {
                            String text = p.getText();
                            if (text != null && text.contains("{{table")) {
                                // 处理{{tableN}}标签
                                Matcher m = Pattern.compile("\\{\\{table(\\d+)\\}\\}").matcher(text);
                                if (m.find()) {
                                    int tableIndex = Integer.parseInt(m.group(1)) - 1;
                                    NodeList tables = xmlDoc.getElementsByTagName("table");
                                    if (tableIndex < tables.getLength()) {
                                        // 插入表格逻辑
                                    } else {
                                        cell.setText("[表格" + (tableIndex + 1) + "不存在]");
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 5. 保存结果
            FileOutputStream out = new FileOutputStream(outputPath);
            doc.write(out);
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void replaceTag(XWPFParagraph p, String tag, String value) {
        for (XWPFRun r : p.getRuns()) {
            String text = r.getText(0);
            if (text != null && text.contains(tag)) {
                r.setText(text.replace(tag, value), 0);
            }
        }
    }

    private static void insertTable(XWPFTableCell cell, Element tableElement) {
        // 清空单元格原有内容
        cell.removeParagraph(0);

        // 创建新段落作为表格容器
        XWPFParagraph para = cell.addParagraph();
        XWPFRun run = para.createRun();

        // 创建新表格
        XWPFTable newTable = cell.getParagraphs().get(0).getDocument().createTable();

        // 3. 复制源表格结构
        NodeList rows = tableElement.getElementsByTagName("tr");
        for (int i = 0; i < rows.getLength(); i++) {
            Element rowElement = (Element) rows.item(i);
            XWPFTableRow newRow = newTable.createRow();

            NodeList cells = rowElement.getElementsByTagName("td");
            for (int j = 0; j < cells.getLength(); j++) {
                Element cellElement = (Element) cells.item(j);

                // 添加单元格
                if (newRow.getTableCells().size() <= j) {
                    newRow.createCell();
                }

                // 设置单元格内容
                XWPFTableCell newCell = newRow.getCell(j);
                newCell.setText(cellElement.getTextContent());

                // 处理合并单元格
                if (cellElement.hasAttribute("colspan")) {
                    int colspan = Integer.parseInt(cellElement.getAttribute("colspan"));
                    newCell.getCTTc().addNewTcPr().addNewGridSpan()
                            .setVal(new java.math.BigInteger(String.valueOf(colspan)));
                }

                if (cellElement.hasAttribute("rowspan")) {
                    int rowspan = Integer.parseInt(cellElement.getAttribute("rowspan"));
                    newCell.getCTTc().addNewTcPr().addNewVMerge()
                            .setVal(org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge.RESTART);
                }
            }
        }

        // 4. 替换原单元格内容为表格
        cell.getParagraphs().get(0).createRun().setText(""); // 清空内容
        // 通过向单元格添加表格内容来实现插入表格
        cell.getCTTc().addNewTbl().set(newTable.getCTTbl()); // 插入表格
    }

    public static void main(String[] args) {
        processTemplate(
                "src/main/resources/templates/模板.docx",
                "src/main/resources/data/DXJG0001A.xml",
                "output/result.docx");
    }
}